//
//  AdvertViewViewModel.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/25.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class AdvertViewViewModel: BaseViewModel {
    @objc dynamic  var refreshBool = false //监听的状态
    var dataArr:Array<Array<CYAdvertItem>> = []
    open var isBuyBool:Bool = true //购买true 卖出 false
    open var inforId:Int? //传递的ID
    open var isChange:Bool = false
    
    lazy var coninKidArray:Array<TradeCoinModel> = {
        let array:Array<TradeCoinModel> = []
        return array
    }()
    var  coinNameArr:Array<String> = []
    var selectCoinModel:TradeCoinModel = TradeCoinModel() //选择的币种
    open var coninKid:String = "" //选择币种
    open var countryStr = kText("中国") //所在地
    var legalCoin = "CNY" //法币币种
    var paymentStyle = kText("支付宝") //付款方式
    
    var securityBool = false //是否启用安全选项
    var trustBool = false //是否启用信任的交易
    
    var openSetBool = false //是否打开高级设置
    var definTimeBool = false //是否打开自定义时间
    
    var timeArr:Array<TimeModel> = [] //自定义时间集合
    var premium:String = "0" //溢价
    var priceStr:String = "" //价格
    var bigAmount:String = "" //最大量
    var smallAmount:String = ""//最小量
    var termStr:String = ""//期限
    var message:String = "" //留言
    
    var lowerPrice:String = "" //最低价
    
    var amountArray:Array<[String : Any]> = [] //用户的资产

    lazy var request: AdvertRequest = {
        let api = AdvertRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    lazy var legalRequest:AssetRequest = {
        let api = AssetRequest()
        api.type = .legalType
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    lazy var advertInforRequest:AdvertInformationRequest = {
        let api = AdvertInformationRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    lazy var changeRequest:ChangeAdverRequest = {
        let api = ChangeAdverRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
   
   override init(controller:BaseViewController) {
       super.init(controller:controller)
    }
    

    
    /// 配置cell信息
    func archiveCellKind() {
        var placeholderArr:Array<Array<String>> = []
        let inforArr = isBuyBool ? KAdverData : KSellAdverData
        var stateArr:Array<Array<Bool>> = []
        var promptArr:Array<Array<String>> = []
        var firArr:Array<CYAdvertItem> = []
        var secondArr:Array<CYAdvertItem> = []
        var thirArr:Array<CYAdvertItem> = []
        var fourArr:Array<CYAdvertItem> = []
        var fiveArr:Array<CYAdvertItem> = []
        var sixArr:Array<CYAdvertItem> = []
        var sevenArr:Array<CYAdvertItem> = []
        var eightArr:Array<CYAdvertItem> = []
        
        if isBuyBool {
            placeholderArr = [["","",""],[kText("价格"),kText("根据市场价的溢价比例"),kText("每一笔交易的最小限额"),kText("每一笔交易的最大限额"),kText("请选择付款方式")]]
            promptArr = [[kText("交易的币种选择"),kText("交易者所在地"),kText("交易的结算货币")],[kText("当前市场价格/溢价之后的交易价格"),kText("在行情价基础上的浮动比率"),kText("交易的起步交易数量"),kText("交易的最大交易数量"),kText("交易的收付款方式")]]
            stateArr = [[false,false,false],[true,false,true,true,false]]
        }else {
            placeholderArr = [["","",""],[kText("价格"),kText("根据市场价的溢价比例"),kText("最低可接受的出售价格"),kText("每一笔交易的最小限额"),kText("每一笔交易的最大限额"),kText("请选择付款方式")]]
            promptArr = [[kText("交易的币种选择"),kText("交易者所在地"),kText("交易的结算货币")],[kText("当前市场价格/溢价之后的交易价格"),kText("在行情价基础上的浮动比率"),kText("最低出售价格，行情低于该价格广告即下架"),kText("交易的起步交易数量"),kText("交易的最大交易数量"),kText("交易的收付款方式")]]
            stateArr = [[false,false,false],[true,false,true,true,true,false]]
        }
        (inforArr as NSArray).enumerateObjects { (array, number, stop) in
            (array as! NSArray).enumerateObjects({ (title, index, end) in
                let item = CYAdvertItem(type: .cyadvertSelectType, name: inforArr[number][index], placeHolder: placeholderArr[number][index], prompt: promptArr[number][index])
                item.isCanWrite = stateArr[number][index]
                if number == 0 {
                    firArr.append(item)
                }else {
                    secondArr.append(item)
                }
            })
        }
        
        let thirItem = CYAdvertItem(type: .cyMessageType, name: "")
        thirArr.append(thirItem)
        let fourItem = CYAdvertItem(type: .cyDefault, name: kText("高级设置 (选填)"))
        fourArr.append(fourItem)
        let fiveItem = CYAdvertItem(type: .cyOpenTimeType, name: kText("开放时间"))
        fiveArr.append(fiveItem)
        if definTimeBool {
            for _ in timeArr {
                let item = CYAdvertItem(type: .cyShowTimeType, name: kText("开放时间"))
                sixArr.append(item)
            }
            let sixItem = CYAdvertItem(type: .cyAddTimeType, name: "")
            sixArr.append(sixItem)
        }
        
        let sevenItem = CYAdvertItem(type: .cySwitchType, name: kText("启用安全选项"))
        sevenArr.append(sevenItem)
        
        let eightItem = CYAdvertItem(type: .cySwitchType, name: kText("仅限受信任的交易者"))
        eightArr.append(eightItem)
        cellfactory.iteamArray = []
        cellfactory.iteamArray.append(firArr)
        cellfactory.iteamArray.append(secondArr)
        cellfactory.iteamArray.append(thirArr)
        cellfactory.iteamArray.append(fourArr)
        if self.openSetBool {
        cellfactory.iteamArray.append(fiveArr)
            if self.definTimeBool {
        cellfactory.iteamArray.append(sixArr)
            }
        cellfactory.iteamArray.append(sevenArr)
        cellfactory.iteamArray.append(eightArr)
        }
    }
    
    
    

    
    /// 获取不同币种对应的信息
    ///
    /// - Parameter coinName: 币种名称 默认BTC CNY
    func archiveCoinInformation(coinName:String,block:@escaping ()->())  {
        self.coninKid = coinName
        AppContext.default.getTradeCoins { (array) in
            self.coninKidArray = array
            self.archiveCoinKind()
            block()
        }
    }
    
    /// 获取法币账户信息
    func archiveLegalAmount()  {
        self.request(request: legalRequest, success: {[weak self] (result) in
            let dic:[String:Any]? = result != nil ? result : nil
            if dic == nil {
                return
            }
            if dic?["data"] as? Array<[String : Any]> == nil  {
                return
            }
            
            self?.amountArray = dic?["data"] as! Array<[String : Any]>
            
        }) { (response) in
            
        }
    }
    
    
    /// 修改广告通过广告id 获取信息
    func archiveAdverInformation() {
        advertInforRequest.inforId = String(format: "%d", inforId ?? 0)
        self.request(request: advertInforRequest, success: {[weak self] (result) in
            if (result?["data"] as? [String:Any]) != nil  {
                let model =  AdverInforModel(JSON: (result?["data"] as? [String:Any])!)
                if model != nil {
                self?.changeInformation(model: model!)
                }
            }
            
        }) { (response) in
            
        }
        
    }
    
    
    /// 发布广告
    func sendInformation() {
        if !self.checkStates() {
            return
        }
        if isChange {
        changeRequest.inforId = String(format: "%d", inforId ?? 0)
        }
        self.request(request: isChange ? changeRequest : request, success: {[weak self] (result) in
            NotificationCenter.default.post(name: NSNotification.Name.Exchange.adListNeedRefresh, object: nil)
            if (self?.isChange)! {
                NotificationCenter.default.post(name: NSNotification.Name.Exchange.adverDidChange, object: nil)
                 CYMBShow.showMessage(kText("修改广告成功"))
            }else {
                CYMBShow.showMessage(kText("发布广告成功"))
            }
            self?.controller?.navigationController?.popViewController(animated: true)
        }) { (fail) in
            CYMBShow.showMessage(fail.errorMsg)
        }
       
    }
    
    
    func archiveCoinKind() {
        var coinArr = [String]()
        for model in self.coninKidArray{
            coinArr.append(model.coinCode?.count != 0 ? model.coinCode! : "")
            if model.coinCode == self.coninKid {
                self.selectCoinModel = model
                self.archiveCoinPrice()
//                self.smallAmount = CYCalculate.cy_intercept(number:  self.selectCoinModel.advertMin != nil ? self.selectCoinModel.advertMin! : 0 , digit: 8)!
            }
        }
       self.coinNameArr = coinArr
    }
    

    /// 获取数字货币对应的法币汇率 计算金额
    func archiveCoinPrice() {
        ///获取汇率
        self.priceStr =  AppContext.default.archiveLegalPrice(coinKind: self.legalCoin, legalKind: self.coninKid)
        self.calculate()
    }
    
    func checkStates() -> Bool {
        if coninKid.count == 0 {
            CYMBShow.showMessage(kText("请选择币种"))
            return false
        }
        if countryStr.count == 0 {
            CYMBShow.showMessage(kText("请选择所在地"))
            return false
        }
        if legalCoin.count == 0 {
            CYMBShow.showMessage(kText("请选择法币币种"))
            return false
        }
        if priceStr.count == 0 {
            CYMBShow.showMessage(kText("请输入价格"))
            return false
        }
        if premium.count == 0 {
            CYMBShow.showMessage(kText("请选择溢价比例"))
            return false
        }
        
        if !isBuyBool && lowerPrice.count == 0 {
            CYMBShow.showMessage(kText("请输入最低价格"))
            return false
        }
        
        if smallAmount.count == 0 {
            CYMBShow.showMessage(kText("请输入最小量"))
            return false
        }
        if bigAmount.count == 0 {
            CYMBShow.showMessage(kText("请输入最大量"))
            return false
        }
        if (bigAmount as NSString).floatValue <= (smallAmount as NSString).floatValue {
            CYMBShow.showMessage(kText("最小量不能大于最大量"))
            return false
        }
        if self.selectCoinModel.advertMin != nil {
        if CYCalculate.campare(firstNumber: (smallAmount as NSString).doubleValue,
                               lastNumber: self.selectCoinModel.advertMin!) == .small {
            CYMBShow.showMessage(kText("最小量不能小于广告呈现最小额"))
            return false
        }
      }
        if self.selectCoinModel.tradeMin != nil {
            if CYCalculate.campare(firstNumber: (smallAmount as NSString).doubleValue,
                                   lastNumber: self.selectCoinModel.tradeMin!) == .small {
            CYMBShow.showMessage(kText("最小量不能小于交易最小额"))
            return false
        }
      }
        if Double(priceStr)! == 0.00 {
            CYMBShow.showMessage(kText("交易价格不能为0"))
            return false
        }
        if !isBuyBool {
        var haveAmount:Bool = false
        for dic in self.amountArray {
            let model = AssetModel(JSON: dic)
            if model?.coinCode == self.coninKid {
                let money = (model?.currentAmount)! * Double(priceStr)!
                if money < (bigAmount as NSString).doubleValue {
                    CYMBShow.showMessage(kText("当前币种余额不足"))
                    return false
                }else {
                    haveAmount = true
                }
            }
        }
        if !haveAmount {
            CYMBShow.showMessage(kText("当前币种余额不足"))
            return false
        }
        }
        if paymentStyle.count == 0 {
            CYMBShow.showMessage(kText("请选择付款方式"))
            return false
        }
        if definTimeBool && timeArr.count == 0 {
            CYMBShow.showMessage(kText("请设置自定义时间"))
            return false
        }
        return true
    }
    
    
    
    /// 修改model的值
    ///
    /// - Parameter result: 结果
    private func changeInformation(model:AdverInforModel) {
        coninKid = model.moneyType.count != 0 ? model.moneyType : ""
        
        let cmodel = Helper.getCountryModel(with: model.address)
        var address = cmodel?.countryChineseName
        if AppCacheInfo.default.isEnlish {
            address = cmodel?.countryEnglishName
        }
        countryStr = address ?? ""
       legalCoin = model.currency.count != 0 ? model.currency : "CNY"
        paymentStyle = model.paymentMethod == 1 ? kText("支付宝") : kText("银联支付")
        securityBool = model.needVerify == 1 ? true : false
        trustBool = model.trustTrade == 1  ? true : false
        definTimeBool = model.openTime == 1 ? true : false
        
//        var timeArr:Array<TimeModel> = [] //自定义时间集合
        premium = String(format: "%d", model.premium != nil ? model.premium!  : "0")
        priceStr = CYCalculate.cy_intercept(number: model.price, digit: 2)!
       bigAmount = CYCalculate.cy_intercept(number: model.limitUpperMoney, digit: 2)!
        smallAmount = CYCalculate.cy_intercept(number: model.limitLowerMoney, digit: 2)!
        message = model.message.count != 0 ? model.message : ""
        for timeModel in model.openTimeList! {
            let timeInfor = TimeModel()
            timeInfor.changeDateInfor(model:timeModel)
            self.timeArr.append(timeInfor)
        }
        
       lowerPrice = CYCalculate.cy_intercept(number: model.lowestPrice, digit: 2)!
        self.archiveCoinInformation(coinName: coninKid, block: {
            DispatchQueue.main.async {
            self.refreshBool = true
            }
        })
    }
    
}

extension AdvertViewViewModel: RequestCallBack,RequestDataReformer,RequestParamSource {
    func reform(_ request: BaseRequest, _ data: [String : Any]?) {
        let block = self.successBlockDic.object(forKey: request.path())
        if ((block as? success) != nil) {
            (block as! success)(data)
        }
    }
    
    func requestDidSucess(_ request: BaseRequest) {
        
    }
    
    func requestDidFail(_ request: BaseRequest) {
        let block = self.failBlockDic.object(forKey: request.path())
        if ((block as? fail) != nil) {
            (block as! fail)(request)
        }
    }
    
    func requestParams(_ request: BaseRequest) -> [String : Any]? {
        var pramas: [String:Any] = [:]
        if (request as? AdvertRequest != nil)  ||  (request as? ChangeAdverRequest != nil) {
        let model = Helper.getCountryModel(with: countryStr)
        let address =  model?.countryChineseName ?? ""
        pramas.updateValue(address, forKey: "address")
        pramas.updateValue(legalCoin, forKey: "currency")
        pramas.updateValue(coninKid, forKey: "moneyType")
        pramas.updateValue(paymentStyle == kText("支付宝") ? 1 : 2, forKey: "paymentMethod")
        pramas.updateValue(premium, forKey: "premium")
        pramas.updateValue(priceStr, forKey: "price")
        pramas.updateValue(smallAmount, forKey: "limitLowerMoney")
        pramas.updateValue(bigAmount, forKey: "limitUpperMoney")
        pramas.updateValue(isBuyBool ? 0 : 1, forKey: "type")
        pramas.updateValue(definTimeBool ? 1 : 0, forKey: "openTime")
        pramas.updateValue(message.count != 0 ? message : "", forKey: "message")
        var syArr:Array<[String:Any]> = []
        if timeArr.count != 0 {
        for model in timeArr {
            var dic:Dictionary<String,Any> = [:]
            dic["openTime"] =  model.openTime
            dic["closeTime"] = model.endTime
            dic["loopDate"] =  model.dateArr
            dic["status"] = 1
            syArr.append(dic)
        }
        let jsonStr:String = syArr.jsonString != nil ?  syArr.jsonString! : ""
        pramas.updateValue(jsonStr, forKey: "openTimeList")
        }
        pramas.updateValue(securityBool ? 1 : 0, forKey: "needVerify")
        pramas.updateValue(trustBool ? 1 : 0, forKey: "trustTrade")
        if !isBuyBool {
            pramas.updateValue(lowerPrice, forKey: "lowestPrice")
        }
       }
        
        return pramas
    }
    
    
    /// 计算溢价后的金额
    func calculate()  {
        var minuteBool = false
        var price = self.premium
        if self.premium.contains("-") {
            price = ((price as? NSString)?.substring(with: NSRange(location: 1, length:price.ch_length-1)))!
            minuteBool = true
        }
        let dePrice = CYCalculate.cy_dividing(firstNumber: price, lastNumber: 100.00, digit: 8)
        if minuteBool {
            let money = CYCalculate.cy_multiplying(firstNumber: self.priceStr, lastNumber: dePrice, digit: 8)
            self.priceStr = CYCalculate.cy_minus(firstNumber: self.priceStr, lastNumber: money, digit: 8)
        }else {
            let money = CYCalculate.cy_multiplying(firstNumber: self.priceStr, lastNumber: dePrice, digit: 8)
            self.priceStr = CYCalculate.cy_add(firstNumber: self.priceStr, lastNumber: money, digit: 8)
        }
        
        
    }
    
}



